const getAuthToken = require("auth-token");
const { Type_DingDing_Web } = require("../../constEnum.js");
const { util } = require("utils");
const { Code2session } = require("./api.js");
const { postRequst } = require("request");
// 拿到token 来解析 code
async function parseCodeByToken(token, code) {
    let url = `${Code2session}?access_token=${token}`;
    let [err, data] = await postRequst(url)({
        code,
    });
    if (!util.nilValue(err)) {
        return [err, null];
    }
    let resData = data || {};
    if (!util.nilValue(resData.errcode) && resData.errcode !== 0) {
        let err = new InsideErr(resData);
        return [err, null];
    } else {
        return [null, resData];
    }
}

async function dingdingWebLogin(appId, appSecret, code) {
    let [token_err, token_data] = await getAuthToken({
        tokenType: Type_DingDing_Web,
        appId,
        appSecret,
    });
    if (!util.nilValue(token_err)) {
        return [token_err, null];
    }
    // 拿到token 来解析 code
    return await parseCodeByToken(token_data, code);
}
module.exports = { dingdingWebLogin };
